package com.cerosoft.api.http;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;

import com.cerosoft.api.exceptions.ConnectionException;
import com.cerosoft.api.exceptions.ResponseException;
import com.cerosoft.api.http.iface.IHttpHandler;
import com.cerosoft.api.http.models.HttpResult;
import com.cerosoft.api.logger.LoggerFactory;

public class RequestExecutor<T> {

	private static final String TAG = "RequestExecutor";

	private HttpUriRequest request;
	private IHttpHandler<T> handler;

	public RequestExecutor(HttpUriRequest request, IHttpHandler<T> handler) {
		this.request = request;
		this.handler = handler;
	}

	public HttpResult<T> execute() throws ConnectionException,
			ResponseException {
		try {
			// Client API specific headers
//			request.setHeader("User-Agent", Config.BN_USER_AGENT);
//			request.setHeader("Referer", Config.BN_REFERRER_NAME);

			// TODO remove logging - copying to avoid concurrent
			// modification
			// exceptions
			// logHttpMessage("REQUEST", request);
			Object[] cookies = HttpClientProxy.getInstance().getCookies()
					.toArray();
			for (Object obj : cookies) {
				Cookie cookie = (Cookie) obj;
				LoggerFactory.getDefaultInstance().information(
						TAG,
						"COOKIE: " + cookie.getName() + " " + cookie.getValue()
								+ " " + cookie.getDomain() + " "
								+ cookie.getPath() + " "
								+ cookie.getExpiryDate());
			}

			// Execute request
			HttpResponse response = HttpClientProxy.getInstance().getClient()
					.execute(request);
			HttpClientHelper.logHttpMessage(TAG, "RESPONSE", response);
			return new HttpResult<T>(response.getStatusLine().getStatusCode(),
					handler.handleResponse(response));
		} catch (ClientProtocolException e) {
			throw new ConnectionException(e);
		} catch (IOException e) {
			throw new ResponseException(e);
		}
	}
}